<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!--  separator-class="el-icon-arrow-right"：设置面包屑中间的连接图标 -->
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>订单管理</el-breadcrumb-item>
      <el-breadcrumb-item>订单列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query">
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getOrderList"
            ></el-button>
          </el-input>
        </el-col>
      </el-row>
      <!-- 订单列表数据 -->
      <el-table :data="orderlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="订单编号" prop="order_number"></el-table-column>
        <el-table-column label="订单价格" prop="order_price"></el-table-column>
        <el-table-column label="是否付款">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.pay_status === 0"
              >已付款</el-tag
            >
            <el-tag type="danger" v-else-if="scope.row.pay_status === 1"
              >未付款</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="是否发货" prop="is_send"></el-table-column>
        <el-table-column label="下单时间">
          <template slot-scope="scope">
            {{ scope.row.create_time | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditAdd(scope.row.order_id)"
            ></el-button>
            <el-button
              size="mini"
              type="success"
              icon="el-icon-location"
              @click="showProgress(scope.row.order_id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 修改地址的对话框 -->
    <el-dialog
      title="修改地址"
      :visible.sync="addressDialogVisible"
      width="50%"
      @close="AddressClose"
    >
      <el-form
        :model="editAddForm"
        :rules="EditAddRules"
        ref="EditAddRef"
        label-width="100px"
      >
        <el-form-item label="省市区/县" prop="address1">
          <el-cascader
            :options="cityData"
            v-model="editAddForm.address1"
            placeholder="请选择省/市/县（区）"
            :props="{ expandTrigger: 'hover' }"
            @change="changeAddress"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address2">
          <el-input v-model="editAddForm.address2"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addressDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="EditAddress">确定</el-button>
      </span>
    </el-dialog>
    <!-- 展示物流进度的对话框 -->
    <el-dialog title="物流进度" :visible.sync="progressVisible" width="50%">
      <el-timeline :reverse="reverse">
        <el-timeline-item
          v-for="(activity, index) in progressInfo"
          :key="index"
          :timestamp="activity.time"
        >
          <!-- timestamp:指定时间轴 -->
          {{ activity.context }}
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script>
import cityData from './cityData.js'
export default {
  data () {
    return {
      queryInfo: {
        query: '',
        pagesize: 10,
        pagenum: 1
      },
      total: 0,
      //   订单列表数据
      orderlist: [],
      //   显示修改地址对话框
      addressDialogVisible: false,
      //    修改地址的表单数据
      editAddForm: {
        address1: [],
        address2: ''
      },
      //  当前的订单号
      orderId: 0,
      //    表单规则
      EditAddRules: {
        address1: [
          { required: true, message: '请选择省市区县', trigger: 'blur' }
        ],
        address2: [
          { required: true, message: '请填写详细地址', trigger: 'blur' }
        ]
      },
      //    地址
      cityData,
      //  展示物流信息对话框
      progressVisible: false,
      //  物流信息列表
      progressInfo: [],
      //  时间轴的排序方式，false：为正序，true：为倒序
      reverse: true
    }
  },
  methods: {
    //  获取当前的订单列表
    async getOrderList () {
      const { data: res } = await this.$http.get('orders', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取订单列表失败')
      }
      this.orderlist = res.data
      this.total = res.total
    },
    //  切换每页显示的数量
    handleSizeChange (newPagesize) {
      this.queryInfo.pagesize = newPagesize
      this.getOrderList()
    },
    //  翻页事件
    handleCurrentChange (newPagenum) {
      this.queryInfo.pagenum = newPagenum
      this.getOrderList()
    },
    //  显示修改地址对话框
    async showEditAdd (orderId) {
      this.orderId = orderId
      const { data: res } = await this.$http.get(`orders/${orderId}`)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      const city = res.data.user_address.split('，')
      const index1 = city[0].indexOf(':')
      const str1 = city[0].substring(index1 + 1)
      const SSQ = str1.split(',')
      const arr = this.getSSQX(SSQ)
      console.log(arr)
      this.editAddForm.address1 = arr
      const index2 = city[1].indexOf(':')
      const str2 = city[1].substring(index2 + 1)
      this.editAddForm.address2 = str2
      this.addressDialogVisible = true
    },
    //  关闭对话框的事件，重置表单
    AddressClose () {
      this.$refs.EditAddRef.resetFields()
    },
    //  展示物流信息对话框
    async showProgress (orderId) {
      const { data: res } = await this.$http.get(`kuaidi/${orderId} `)
      if (res.meta.status !== 200) {
        return this.$message.error('获取物流信息失败')
      }
      this.progressInfo = res.data
      this.progressVisible = true
    },
    //  选择省市区/县
    changeAddress () {
      console.log(this.editAddForm.address1)
    },
    //  抽出当前订单的省市区县的value
    getSSQX (SSQ) {
      const arr = []
      this.cityData.some((item) => {
        if (item.label === SSQ[0]) {
          arr.push(item.value)
          if (item.children) {
            item.children.some((item1) => {
              if (item1.label === SSQ[1]) {
                arr.push(item1.value)
                if (item1.children) {
                  item1.children.some((item2) => {
                    if (item2.label === SSQ[2]) {
                      arr.push(item2.value)
                    }
                  })
                }
              }
            })
          }
        }
      })
      return arr
    },
    getSSQXvalue (SSQ) {
      console.log(SSQ)
      const arr = []
      SSQ.forEach((item) => {
        this.cityData.forEach((item1) => {
          if (item1.value === item) {
            return arr.push(item1.label)
          }
          item1.children.forEach((item2) => {
            if (item2.value === item) {
              return arr.push(item2.label)
            }
            if (item2.children) {
              item2.children.forEach((item3) => {
                if (item3.value === item) {
                  return arr.push(item3.label)
                }
              })
            }
          })
        })
      })
      return arr
    },
    //  修改收货地址
    async EditAddress (orderId) {
      const editAddForm = { address1: '', address2: '' }
      const arr = this.getSSQXvalue(this.editAddForm.address1).join(',')
      editAddForm.address1 = arr
      editAddForm.address2 = this.editAddForm.address2
      const { data: res } = await this.$http.put(
        `orders/${this.orderId}`,
        editAddForm
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改收货地址失败')
      }
      this.$message.success('修改订单收货地址成功')
      this.addressDialogVisible = false
    }
  },
  created () {
    this.getOrderList()
  }
}
</script>

<style lang="less" scoped></style>
